package com.smartleanx.module.hrm.controller.admin.employee;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.smartleanx.framework.common.pojo.CommonResult;
import com.smartleanx.framework.common.pojo.PageParam;
import com.smartleanx.framework.common.pojo.PageResult;
import com.smartleanx.framework.common.util.collection.CollectionUtils;
import com.smartleanx.framework.common.util.object.BeanUtils;
import com.smartleanx.framework.common.validation.ValidatedGroup;
import com.smartleanx.framework.customfield.core.service.bo.CustomFieldDataRespBO;
import com.smartleanx.framework.excel.core.util.ExcelUtils;
import com.smartleanx.framework.security.core.annotations.PreAuthenticated;
import com.smartleanx.module.hrm.controller.admin.employee.login.EmployeeLoginInfoPageReqVO;
import com.smartleanx.module.hrm.controller.admin.employee.login.EmployeeLoginInfoRespVO;
import com.smartleanx.module.hrm.controller.admin.employee.login.EmployeeLoginInfoSaveReqVO;
import com.smartleanx.module.hrm.controller.admin.employee.regularizerecord.EmployeeRegularizeRecordRespVO;
import com.smartleanx.module.hrm.controller.admin.employee.regularizerecord.EmployeeRegularizeRecordSaveReqVO;
import com.smartleanx.module.hrm.controller.admin.employee.vo.*;
import com.smartleanx.module.hrm.convert.employee.contract.EmployeeConvert;
import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeDO;
import com.smartleanx.module.hrm.framework.excel.CustomCellWriteWidthConfig;
import com.smartleanx.module.hrm.framework.excel.MonthSheetWriteHandler;
import com.smartleanx.module.hrm.framework.excel.SpinnerWriteHandler;
import com.smartleanx.module.hrm.framework.excelUtil.HiddenColumn;
import com.smartleanx.module.hrm.intergration.AdminUserServiceProvider;
import com.smartleanx.module.hrm.intergration.DeptServiceProvider;
import com.smartleanx.module.hrm.service.employee.EmployeeService;
import com.smartleanx.module.hrm.service.employee.EmployeeTransferRecordService;
import com.smartleanx.module.hrm.service.employee.bo.EmployeeFileRespBo;
import com.smartleanx.module.infra.api.file.dto.FileRefRespDTO;
import com.smartleanx.module.system.api.customfield.dto.CustomFieldRespDTO;
import com.smartleanx.module.system.api.dept.dto.DeptRespDTO;
import com.smartleanx.module.system.api.user.dto.AdminUserPageReqDTO;
import com.smartleanx.module.system.api.user.dto.AdminUserRespDTO;
import com.smartleanx.module.system.enums.customfield.CustomFieldTypeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.smartleanx.framework.common.pojo.CommonResult.success;
import static com.smartleanx.framework.common.util.collection.CollectionUtils.convertList;
import static com.smartleanx.framework.common.util.collection.CollectionUtils.convertSet;

@Tag(name = "管理后台 - 员工")
@RestController
@RequestMapping("/hrm/employee")
@Validated
@Slf4j
public class EmployeeController {

    @Resource
    private EmployeeService employeeService;

    @Resource
    private DeptServiceProvider deptServiceProvider;

    @Resource
    private EmployeeTransferRecordService transferRecordService;

    @Resource
    private AdminUserServiceProvider adminUserServiceProvider;


    @GetMapping("/selectEmployeeBySelect")
    public CommonResult<Object> selectEmployeeBySelect(@RequestParam(value = "employeeName", required = false) String employeeName) {

        return success(employeeService.selectEmployeeBySelect(employeeName));
    }

    @PostMapping("/create")
    @Operation(summary = "创建员工")
    @PreAuthorize("@ss.hasPermission('hrm:employee:create')")
    public CommonResult<Long> createEmployee(@Valid @RequestBody List<EmployeeFieldSaveReqVo> createReqVO) {
        return success(employeeService.createEmployee(createReqVO));
    }

    @PostMapping("/createEmployeeOnTrial")
    @Operation(summary = "创建试用账号")
//    @PreAuthorize("@ss.hasScope('user:create')")
    public CommonResult<JSONObject> createEmployeeOnTrial(@RequestBody EmployeeOnTrialReqVo reqVo) {
        JSONObject result = new JSONObject();
        employeeService.createEmployeeOnTrial(reqVo);
        result.put("message", "操作成功");
        return success(result);
    }

    @PutMapping("/update")
    @Operation(summary = "更新员工")
    @PreAuthorize("@ss.hasPermission('hrm:employee:update')")
    public CommonResult<Boolean> updateEmployee(@Valid @RequestBody EmployeeSaveReqVO saveReqVO) {
        employeeService.updateEmployee(saveReqVO);
        return success(true);
    }

    @PutMapping("/updateStatus")
    @Operation(summary = "更新员工状态")
    @PreAuthorize("@ss.hasPermission('hrm:employee:updateStatus')")
    public CommonResult<Boolean> updateEmployeeStatus(@Valid @RequestBody EmployeeUpdateStatusReqVO updateStatusReqVO) {
        employeeService.updateEmployeeStatus(updateStatusReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除员工")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('hrm:employee:delete')")
    public CommonResult<Boolean> deleteEmployee(@RequestParam("id") Long id) {
        employeeService.deleteEmployee(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得员工信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<List<List<CustomFieldDataRespBO>>> getEmployeeField(@RequestParam("id") Long id,
                                                                            @RequestParam("label") Integer label,
                                                                            @RequestParam("labelGroup") Integer labelGroups) throws IllegalAccessException {
        return success(employeeService.getEmployeeField(id, label, labelGroups));
    }

    @GetMapping("/page")
    @Operation(summary = "获得员工分页")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<PageResult<EmployeePageRespVO>> getEmployeePage(@Valid EmployeePageReqVO pageReqVO) {
        PageResult<EmployeePageRespVO> pageResult = employeeService.getEmployeePage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/countStatusNum")
    @Operation(summary = "获得员工各个状态数量")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<List<EmployeeStatusCountRespVO>> countStatusNum(@Valid EmployeePageReqVO pageReqVO) {
        return success(employeeService.countStatusNum(pageReqVO));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出员工 Excel")
    @PreAuthorize("@ss.hasPermission('hrm:employee:export')")
    public void exportEmployeeExcel(@Valid EmployeePageReqVO pageReqVO,
                                    HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<EmployeeExportVo> list = employeeService.getExportEmployeeExcel(pageReqVO);
        // 导出 Excel
        ExcelUtils.write(response, "员工.xlsx", "数据", EmployeeExportVo.class,
                list);
    }

    @PostMapping("/regularize")
    @Operation(summary = "转正")
    @PreAuthorize("@ss.hasPermission('hrm:employee:regularize')")
    public CommonResult<Boolean> regularize(@RequestBody @Valid EmployeeRegularizeRecordSaveReqVO regularizeReqVO) {
        employeeService.regularize(regularizeReqVO);
        return success(true);
    }

    @PostMapping("/employeeRegularize")
    @Operation(summary = "员工提交转正申请")
    @PreAuthorize("@ss.hasPermission('hrm:employee:regularize')")
    public CommonResult<Boolean> employeeRegularize(@RequestBody @Valid EmployeeRegularizeRecordSaveReqVO regularizeReqVO) {
        employeeService.employeeRegularize(regularizeReqVO);
        return success(true);
    }

    @PostMapping("/changePost")
    @Operation(summary = "调动")
    @PreAuthorize("@ss.hasPermission('hrm:employee:changePost')")
    public CommonResult<Boolean> changePost(@RequestBody @Valid EmployeeChangePostSaveReqVO changePostReqVO) {
        employeeService.changePost(changePostReqVO);
        return success(true);
    }

    @PostMapping("/employeeChangePost")
    @Operation(summary = "员工端操作调动")
    @PreAuthorize("@ss.hasPermission('hrm:employee:changePost')")
    public CommonResult<Boolean> employeeChangePost(@RequestBody @Valid EmployeeChangePostSaveReqVO changePostReqVO) {
        employeeService.employeeChangePost(changePostReqVO);
        return success(true);
    }


    @PostMapping("/leave")
    @Operation(summary = "离职")
    @PreAuthorize("@ss.hasPermission('hrm:employee:leave')")
    public CommonResult<Boolean> leave(@RequestBody @Valid EmployeeLeaveReqVO leaveReqVO) {
        employeeService.leave(leaveReqVO);
        return success(true);
    }

    @PostMapping("/employeeLeave")
    @Operation(summary = "用户提交离职申请")
    @PreAuthorize("@ss.hasPermission('hrm:employee:leave')")
    public CommonResult<Boolean> employeeLeave(@RequestBody @Valid EmployeeLeaveReqVO leaveReqVO) {
        employeeService.employeeLeave(leaveReqVO);
        return success(true);
    }

    // @PostMapping("/cancelLeave")
    // @Operation(summary = "取消离职")
    // @PreAuthorize("@ss.hasPermission('hrm:employee:leave')")
    // public CommonResult<Boolean> cancelLeave(@RequestBody @Valid EmployeeCancelLeaveReqVO cancelLeaveReqVO) {
    //     employeeService.cancelLeave(cancelLeaveReqVO);
    //     return success(true);
    // }
    //
    // @PostMapping("/updateLeaveInfo")
    // @Operation(summary = "更改离职信息")
    // @PreAuthorize("@ss.hasPermission('hrm:employee:leave')")
    // public CommonResult<Boolean> updateLeaveInfo(@RequestBody @Valid EmployeeLeaveReqVO leaveReqVO) {
    //     employeeService.updateLeaveInfo(leaveReqVO);
    //     return success(true);
    // }

    @GetMapping("/logPage")
    @Operation(summary = "查看员工信息操作记录")
    @PreAuthorize("@ss.hasPermission('hrm:employee:log')")
    public CommonResult<PageResult<EmployeeLogRespVO>> getEmployeeActionLog(@Valid EmployeeLogReqVO logReqVO) {
        PageResult<EmployeeLogRespVO> logRespVOList = employeeService.getEmployeeActionLog(logReqVO);
        return success(logRespVOList);
    }

    @PutMapping("/addFile")
    @Operation(summary = "添加附件")
    @PreAuthorize("@ss.hasPermission('hrm:employee:update')")
    public CommonResult<Boolean> addFile(@RequestBody @Valid EmployeeAddFileReqVO addFileReqVO) {
        employeeService.addFile(addFileReqVO);
        return success(true);
    }

    @GetMapping("/getFileListByFileType")
    @Operation(summary = "根据附件类型获取员工的文件列表")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<List<FileRefRespDTO>> getFileListByFileType(@RequestBody @Valid EmployeeAddFileReqVO addFileReqVO) {
        return success(employeeService.getFileListByFileType(addFileReqVO));
    }

    @GetMapping("/getEmployeeRegularize")
    @Operation(summary = "获取员工转正申请信息")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<EmployeeRegularizeRecordRespVO> getEmployeeRegularize(@RequestParam("id") Long id) {
        return success(employeeService.getEmployeeRegularize(id));
    }

    @GetMapping("/getEmployeeChangePost")
    @Operation(summary = "获取员工调动记录信息")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<EmployeeChangePostRespVO> getEmployeeChangePost(@RequestParam("id") Long id) {
        return success(employeeService.getEmployeeChangePost(id));
    }

    @GetMapping("/getEmployeeLeave")
    @Operation(summary = "获取员工离职申请信息")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<EmployeeLeaveRespVO> getEmployeeLeave(@RequestParam("id") Long id) {
        return success(employeeService.getEmployeeLeave(id));
    }

    @GetMapping("/employeeFiles")
    @Operation(summary = "获取员工附件（管理端）")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<List<EmployeeFileRespBo>> employeeFiles(@RequestParam("id") Long id) {
        return success(employeeService.employeeFiles(id, true));
    }

    @GetMapping("/getEmployeeInfo")
    @Operation(summary = "获取员工基本信息")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<EmployeeBasicInfoRespVo> getEmployeeInfo(@RequestParam("id") Long id) {
        return success(employeeService.getEmployeeInfo(id));
    }

    @GetMapping("/getEmployeeList")
    @Operation(summary = "获取员工列表")
    @PreAuthenticated
    public CommonResult<List<EmployeeLeaderRespVo>> getEmployeeList(@RequestParam(value = "name", required = false) String name) {
        return success(employeeService.getEmployeeList(name));
    }

    @PostMapping("/createEmployeeFileRef")
    @Operation(summary = "创建员工附件关联关系")
    @PreAuthorize("@ss.hasPermission('hrm:employee:update')")
    public CommonResult<Boolean> createEmployeeFileRef(@RequestBody @Valid EmployeeFileReqVo vo) {
        return success(employeeService.createEmployeeFileRef(vo));
    }

    @GetMapping("/getEmployeeOverview")
    @Operation(summary = "首页仪表盘人事概况")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<List<EmployeeOverviewRespVo>> getEmployeeOverview() {
        return success(employeeService.getEmployeeOverview());
    }

    @GetMapping("/getEmployeeToDoReminder")
    @Operation(summary = "首页仪表盘待办提醒")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<EmployeeToDoReminderRespVo> getEmployeeToDoReminder() {
        return success(employeeService.getEmployeeToDoReminder());
    }

    @GetMapping("/getOnTheJob")
    @Operation(summary = "首页仪表盘在职员工")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<EmployeeOnTheJobRespVo> getOnTheJob() {
        return success(employeeService.getOnTheJob());
    }

    @GetMapping("/getBirthdayPage")
    @Operation(summary = "首页仪表盘生日弹窗分页")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<PageResult<EmployeePageRespVO>> getBirthdayPage(@Valid EmployeeDashboardPageReqVO pageReqVO) {
        return success(employeeService.getBirthdayPage(pageReqVO));
    }

    @GetMapping("/getAnniversaryEmployeePage")
    @Operation(summary = "获取入职周年员工分页")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<PageResult<EmployeePageRespVO>> getAnniversaryEmployeePage(EmployeeDashboardPageReqVO pageReqVO) {
        return success(employeeService.getAnniversaryEmployeePage(pageReqVO));
    }

    @GetMapping("/getNotifyRegularizeEmployeePage")
    @Operation(summary = "待转正员工提醒（提前7天/15天） 弹窗")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<PageResult<EmployeePageRespVO>> getNotifyRegularizeEmployeePage(EmployeeDashboardPageReqVO pageReqVO) {
        return success(employeeService.getNotifyRegularizeEmployeePage(pageReqVO));
    }

    @GetMapping("/getContractExpirationPage")
    @Operation(summary = "首页仪表盘合同到期弹窗分页")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<PageResult<EmployeePageRespVO>> getContractExpirationPage(@Valid EmployeeDashboardPageReqVO pageReqVO) {
        return success(employeeService.getContractExpirationPage(pageReqVO));
    }

    /**
     * @author wyq
     * 获取导入模板
     */
    @GetMapping("/downloadExcel")
    @Operation(summary = "获取导入模板")
    public void download(HttpServletResponse response) throws IOException {
        List<CustomFieldRespDTO> hrmEmployeeFields = employeeService.downloadExcelFiled();

        List<List<String>> date = new ArrayList<>();
        // 构建
        int num = 0; // 列号
        Map<Integer, String[]> mapDropDown = new HashMap<>(); // 下拉列表
        for (CustomFieldRespDTO dto : hrmEmployeeFields) {
            List<String> list = new ArrayList<>();
            String name = dto.getName();
            if (!dto.getIsNull()) {
                //标记必填
                name = "*" + name;
            }
            if (dto.getType().equals(CustomFieldTypeEnum.DATE.getValue())) {
                name += "-(例:[2024年10月1日])";
            }
            // 构建下拉选项
            List<Integer> type = Stream.of(CustomFieldTypeEnum.RADIO.getValue(), CustomFieldTypeEnum.CHECKBOX.getValue(),
                    CustomFieldTypeEnum.SINGLE_SELECT.getValue(), CustomFieldTypeEnum.MULTI_SELECT.getValue()
                    , CustomFieldTypeEnum.POST.getValue(), CustomFieldTypeEnum.DEPT.getValue()).collect(Collectors.toList());
            if (type.contains(dto.getType())) {
                String options = dto.getOptions();
                if (StrUtil.isNotEmpty(options)) {
                    List<String> setting = new ArrayList<>();
                    if (JSONUtil.isJsonArray(options)) {
                        JSONArray array = new JSONArray(options);
                        for (int j = 0; j < array.size(); j++) {
                            setting.add(array.getJSONObject(j).get("label", String.class));
                        }
                    }
                    String[] select = setting.stream().toArray(String[]::new);

                    mapDropDown.put(num, select);
                }
            }
            list.add(name);
            date.add(list);
            num += 1;
        }
        String fileName = "员工导入模板.xlsx";
        exportExcel(response, fileName, date, mapDropDown, null, "员工导入模板(*)为必填项；正式员工，要选择试用期，非正式员工要选择非正式类型");


    }

    /**
     * 动态表头导出
     *
     * @param response    HttpServletResponse
     * @param fileName    文件名
     * @param Myhead      Excel表头信息
     * @param mapDropDown 单元格数据校验（下拉选项）
     * @param data        Excel数据
     * @param titleRow    首行标题
     */
    public static void exportExcel(HttpServletResponse response, String fileName, List<List<String>> Myhead,
                                   Map<Integer, String[]> mapDropDown, List<List<Object>> data, String titleRow) {
        try {

            //1 设置下载相关内容
            //设置mime类型
            response.setContentType("application/vnd.ms-excel");
            //设置编码
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            fileName = URLEncoder.encode(fileName, "UTF-8");
            //设置响应头信息 Content-disposition
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                    .autoCloseStream(false)// 不要自动关闭，交给 Servlet 自己处理
                    .build();

            WriteSheet writeSheet = EasyExcel.writerSheet(0, "员工导入模板")
                    .registerWriteHandler(new SpinnerWriteHandler(mapDropDown))
                    .registerWriteHandler(new CustomCellWriteWidthConfig()) // 基于 column 长度，自动适配。最大 255 宽度
                    .relativeHeadRowIndex(1).registerWriteHandler(new MonthSheetWriteHandler(titleRow, Myhead.size()))
                    .head(Myhead).build();
            excelWriter.write(new ArrayList<>(), writeSheet);

//          下拉选项隐藏Sheet
            Workbook workbook =
                    excelWriter.writeContext().writeSheetHolder().getParentWriteWorkbookHolder().getWorkbook();
            if (!mapDropDown.keySet().isEmpty()) {
                int sheetNo = 1;
                for (Map.Entry<Integer, String[]> entry : mapDropDown.entrySet()) {
                    String[] values = entry.getValue();

                    if (values.length < SpinnerWriteHandler.LIMIT) {
                        continue;
                    }
                    List<HiddenColumn> sheetData = new ArrayList<>();
                    for (String s : values) {
                        sheetData.add(new HiddenColumn(s));
                    }
                    // 下拉sheet
                    WriteSheet dropSheet = EasyExcel.writerSheet(sheetNo, entry.getKey().toString())
                            // 设置并隐藏表头
                            .head(HiddenColumn.class).needHead(false).build();
                    excelWriter.write(sheetData, dropSheet);
                    // 隐藏辅助Sheet
                    workbook.setSheetHidden(sheetNo, true);

                    sheetNo++;
                }
            }

            excelWriter.finish();


//            EasyExcel.write(response.getOutputStream())
//                    .autoCloseStream(false) // 不要自动关闭，交给 Servlet 自己处理
//                    .registerWriteHandler(new CustomCellWriteWidthConfig()) // 基于 column 长度，自动适配。最大 255 宽度
//                    .head(Myhead)
//                    .sheet("员工导入模板")
//                    .registerWriteHandler(new SpinnerWriteHandler(mapDropDown))
//                    .relativeHeadRowIndex(1).registerWriteHandler(new MonthSheetWriteHandler(titleRow, Myhead.size()))
//                    .doWrite(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 动态表头导入功能
     *
     * @param file 文件
     * @return
     */
    @PostMapping("/importExcel")
    @Operation(summary = "导入员工")
    @PreAuthorize("@ss.hasPermission('hrm:employee:import')")
    public CommonResult<EmployeeImportRespVO> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        return success(employeeService.importExcel(file));
    }

    @GetMapping("/getEmployeeSeparation")
    @Operation(summary = "获取员工离职信息（员工档案编辑用）")
    @PreAuthenticated
    public CommonResult<EmployeeSeparationRespVo> getEmployeeSeparation(@RequestParam("employeeId") Long employeeId) {
        return success(employeeService.getEmployeeSeparation(employeeId));
    }

    @PostMapping("createLoginInfo")
    @Operation(summary = "创建员工登录信息")
    @PreAuthorize("@ss.hasPermission('system:user:create')")
    public CommonResult<Boolean> createLoginInfo(@Validated(ValidatedGroup.CreateGroup.class)
                                                 @RequestBody EmployeeLoginInfoSaveReqVO reqVO) {
        employeeService.createLoginInfo(reqVO);
        return success(true);
    }

    @GetMapping("getLoginInfo")
    @Operation(summary = "获取员工登录信息")
    @Parameter(name = "id", description = "用户编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<EmployeeLoginInfoRespVO> getLoginInfo(@RequestParam("id") Long userId) {
        return success(employeeService.getLoginInfo(userId));
    }

    @GetMapping("/loginInfoPage")
    @Operation(summary = "获得员工登录信息分页列表")
    @PreAuthorize("@ss.hasPermission('system:user:list')")
    public CommonResult<PageResult<EmployeeLoginInfoRespVO>> getLoginInfoPage(@Valid EmployeeLoginInfoPageReqVO pageReqVO) {
        AdminUserPageReqDTO userPageReqDTO = EmployeeConvert.INSTANCE.convertLoginInfoPageReqDTO(pageReqVO);
        if (pageReqVO.getEmployeeId() != null) {
            EmployeeDO employee = employeeService.getEmployeeById(pageReqVO.getEmployeeId());
            if (employee == null) {
                return success(PageResult.empty());
            }
            Long userId = employee.getUserId();
            if (userId == null) {
                return success(PageResult.empty());
            }
            userPageReqDTO.setId(userId);
        }
        // 获得用户分页列表
        PageResult<AdminUserRespDTO> pageResult = adminUserServiceProvider.getUserPage(userPageReqDTO);

        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        // 拼接数据
        Map<Long, DeptRespDTO> deptMap = deptServiceProvider.getDeptMap(convertSet(pageResult.getList(), AdminUserRespDTO::getDeptId));
        Map<Long, EmployeeDO> employeeLoginInfoMap = CollectionUtils.convertMap(
                employeeService.getEmployeeByUserIds(convertSet(pageResult.getList(), AdminUserRespDTO::getId)), EmployeeDO::getUserId
        );

        return success(
                new PageResult<>(
                        EmployeeConvert.INSTANCE.convertLoginInfoList(pageResult.getList(), deptMap, employeeLoginInfoMap), pageResult.getTotal()
                )
        );
    }

    @GetMapping("/loginInfo/list-simple")
    @Operation(summary = "模糊查询绑定登录账号的员工精简信息列表", description = "主要用于前端的下拉选项")
    @PreAuthenticated
    public CommonResult<List<EmployeeSimpleRespVO>> getLoginEmpList(EmployeeLikeQueryReqVO queryReqVO) {
        List<EmployeeDO> list = employeeService.getLoginEmpList(queryReqVO);
        return success(BeanUtils.toBean(list, EmployeeSimpleRespVO.class));
    }

    @PutMapping("updateLoginInfo")
    @Operation(summary = "更新员工登录信息")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateLoginInfo(@Validated(ValidatedGroup.UpdateGroup.class)
                                                 @RequestBody EmployeeLoginInfoSaveReqVO reqVO) {
        employeeService.updateLoginInfo(reqVO);
        return success(true);
    }

    @DeleteMapping("/deleteLoginInfo")
    @Operation(summary = "删除员工登录信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        employeeService.deleteLoginInfo(id);
        return success(true);
    }

    @GetMapping("/list-simple")
    @Operation(summary = "模糊查询员工精简信息列表", description = "主要用于前端的下拉选项")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<List<EmployeeSimpleRespVO>> getEmployeeSimpleList(@Valid EmployeeLikeQueryReqVO queryReqVO) {
        List<EmployeeDO> list = employeeService.getEmployeeSimpleList(queryReqVO);
        Map<Long, DeptRespDTO> deptMap = deptServiceProvider.getDeptMap(convertList(list, EmployeeDO::getDeptId));
        return success(EmployeeConvert.INSTANCE.convertSimpleList(list, deptMap));
    }

    @GetMapping("/employeeDeptPage")
    @Operation(summary = "按照组织结构获取员工分页列表")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<PageResult<EmployeeDeptPageRespVo>> employeeDeptPage(@Valid EmployeeDeptPageReqVo reqVo) {
        return success(employeeService.employeeDeptPage(reqVo));
    }

    @GetMapping("/changesGroups")
    @Operation(summary = "按照附件类型获取调动记录")
    @PreAuthorize("@ss.hasPermission('hrm:employee:query')")
    public CommonResult<List<EmployeeTransferSimpleRespVo>> changesGroups(@RequestParam("employeeId") Long employeeId, @RequestParam("bizFileType") Integer bizFileType) {
        return success(transferRecordService.changesGroups(employeeId, bizFileType));
    }

    @PostMapping("/createChangesFiles")
    @Operation(summary = "创建管理端补充的调动记录附件关联关系")
    @PreAuthorize("@ss.hasPermission('hrm:employee:update')")
    public CommonResult<Boolean> createChangesFiles(@RequestBody EmployeeChangesFilesSaveReqVO reqVO) {
        transferRecordService.createChangesFiles(reqVO);
        return success(true);
    }

    @Operation(summary = "下载客户导入失败数据")
    @GetMapping("/importDownload")
    public void importDownload(HttpServletResponse response, String fileName, String filePath) {
        try {
//            String filePath = "C:\\Users\\a\\AppData\\Local\\Temp\\" + fileName;
//            String filePath = "/tmp/" + fileName;

            File tempFile = new File(filePath);
            try (FileInputStream fis = new FileInputStream(tempFile)) {
                byte[] buffer = new byte[fis.available()];
                int read = fis.read(buffer);
                //设置mime类型
                response.setContentType("application/octet-stream");
                //设置编码
                response.setCharacterEncoding("utf-8");
                //设置响应头信息 Content-disposition
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            }
        } catch (Exception e) {
            log.error("文件导出下载报错message {}", e.getMessage());
        }
    }


    @GetMapping("/sendMessage")
    @PermitAll
    public CommonResult<Object> sendMessage(@RequestParam("tenantName") String tenantName, @RequestParam("phone") String phone, @RequestParam("account") String account) {
        Integer i = employeeService.sendMessage(tenantName, phone, account);

        return CommonResult.success("发送成功");
    }

    @GetMapping("/retrievePassword")
    @PermitAll
    public CommonResult<Object> retrievePassword(@RequestParam("tenantName") String tenantName, @RequestParam("phone") String phone, @RequestParam("account") String account, @RequestParam("messageCode") String messageCode, @RequestParam("password") String code) {
        Integer i = employeeService.retrievePassword(tenantName, phone, account, messageCode, code);
        return CommonResult.success("修改成功");

    }

    @GetMapping("/selectAuthorizedStatus")
    public CommonResult<Object> selectAuthorizedStatus() {

        return CommonResult.success(employeeService.selectAuthorizedStatus());

    }
    @GetMapping("/selectPsnInfo")
    public CommonResult<Object> selectPsnInfo() {
        return CommonResult.success( employeeService.selectPsnInfo());

    }
}
